import requests
import os
import sys
from bs4 import BeautifulSoup

def Req(url):
    return requests.get(url=url,headers=GetHeaders())
def GetHeaders():
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
    return headers

def GetBookUrl():
    book_url = "https://mp.weixin.qq.com/s?__biz=MzU2MjM5ODQ5OA==&mid=2247551565&idx=2&sn=576a67757b44e759a4de09623530af32&chksm=fd4b5d3d374b96e272057929f94cfd41dc3e14139c58a4a2f9169f3575cb260c3b2905c8e3e7&mpshare=1&srcid=0918qWq4VSZNCTQy5jX8LLta&sharer_shareinfo=6b7b39a911937af700a880e9a12fb789&sharer_shareinfo_first=6b7b39a911937af700a880e9a12fb789&from=singlemessage&scene=1&subscene=10000&sessionid=1758176179&clicktime=1758199260&enterid=1758199260&ascene=1&fasttmpl_type=0&fasttmpl_fullversion=7912993-zh_CN-zip&fasttmpl_flag=0&realreporttime=1758199260907&devicetype=android-34&version=28003d31&nettype=WIFI&abtest_cookie=AAACAA%3D%3D&lang=zh_CN&countrycode=CN&exportkey=n_ChQIAhIQUT5%2FIkH39TUHL%2F9VYSsJrxL2AQIE97dBBAEAAAAAAGCOI1QbbpkAAAAOpnltbLcz9gKNyK89dVj0HM%2Fs5jI%2B3bMm2MYdZaD9SxcOjSMqBtSQUoFy6WtGm0FmvGxrrJ5ZIj9l7bFxmJeg%2BdsBYIr3BKvgyshFt0QoThRS3MwT2wFhetfcyn6jpqOGhBc7JNSyHnrWoVTMkUp%2FyHt9MpdUmR7%2F65R5KIG%2BgZJo%2Btr9GMqkVcRLdy8C4IWIsJl7qatHdwwoejf%2BP70TEvxDbb%2FqN9G8OHGadpn2WmZ7SbMkiYQmyuehMbiZ7p0rVAtu4lWXX%2BD1F1HmjWaouQtOQ%2BK0ZQDv%2F0WOOWEwRw%3D%3D&pass_ticket=WyCrJgIUqz8LmtgscxuTnpVZkAsIS1v%2B6QKK%2BLUfxlPzTnDe6AyNyXPmdsw5uq9x&wx_header=3"
    # book_url="http://httpbin.org/get"
    html= Req(book_url).text
    # print(html)
    soup = BeautifulSoup(html, 'html.parser')
    links = soup.select('#js_content .normal_text_link') 
    # print(links)
    res=[]
    for link in links:
        l={
            "url":link.get("href"),
            "name":link.text

        }
        res.append(l)
    return res
def Mkdir(dir_path):
    dir_path = format_book_name(dir_path)
    # print(dir_path)
    os.makedirs(dir_path,exist_ok=True)
def Dowload_Mp3(URL,BOOK_PATH,BOOK_NAME):
    count=5
    i=0
    while i<count:
        # print("下载次数"+str(i))
        res=requests.get(URL, stream=True,verify=False)
        if res.status_code == 200:
            print("写入文件"+format_book_name( BOOK_PATH))
            with open(format_book_name( BOOK_PATH), 'wb') as f:
                f.write(res.content)
                print(BOOK_NAME + "下载完成!")
            break
        else:
            print("下载失败！正在重试！重试次数"+str(i))
        if res.status_code != 200:
            sys.exit()
 
           
     
def format_book_name(name):
    name = "m6/"+name
    name= name.replace("|", "_")  
    return name
def main():
    print("main")
if __name__ == '__main__':
    book_urls =GetBookUrl()
    # print(book_urls)
    start_book=58
    for i, book in enumerate(book_urls[start_book:], start=start_book):
        print(i)
        Mkdir( book["name"])
       
        # print(book.url)
        html= Req(book["url"]).text
        soup = BeautifulSoup(html, 'html.parser')
        mp3s = soup.select('#js_content .js_editor_audio') 
        for mp3 in mp3s:
           fid= mp3.get("voice_encode_fileid")
           book_name=mp3.get("name")
           print("正在下载-->" +book_name )
           voice_url = "https://res.wx.qq.com/voice/getvoice?mediaid=" + fid
        #    print(voice_url)
           Dowload_Mp3(voice_url,book["name"]+"/"+book_name+".mp3",book_name)
            
